package com.lgl.mes.common.util.org.easy.excel.util;

import org.springframework.util.ConcurrentReferenceHashMap;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 日期转换处理工具类， 同一个pattern格式，使用同一个PatternFormat对象处理
 * 同一个PatternFormat对象，在多线程竞争的情况下确保线程安全，使用同一个SimpleDateFormat对象来保证日期解析的性能
 * 
 * @author lisuo
 *
 */
public class FastDateUtil {
	
	//内部空间不足可以被回收
	private static Map<String, PatternFormat> map = new ConcurrentReferenceHashMap<>();

	/**
	 * 字符转日期
	 * @param dateStr
	 * @param patterns
	 * @return
	 */
	public static Date parse(String dateStr, String... patterns) {
		if (patterns != null && patterns.length > 0) {
			for (String pattern : patterns) {
				try {
					return get(pattern).parse(dateStr);
				} catch (Exception ignore) {
					continue;
				}
			}
		}
		return null;
	}

	/**
	 * 日期转字符
	 * @param date
	 * @param pattern 
	 * @return
	 */
	public static String format(Date date, String pattern) {
		return get(pattern).format(date);
	}

	private static PatternFormat get(String pattern) {
		PatternFormat pf = map.get(pattern);
		if (pf == null) {
			synchronized (map) {
				pf = map.get(pattern);
				if (pf == null) {
					pf = new PatternFormat(pattern);
					map.put(pattern, pf);
				}
			}
		}
		return pf;
	}

	static class PatternFormat {

		private String pattern;

		public PatternFormat(String pattern) {
			this.pattern = pattern;
		}

		private ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
			@Override
			protected DateFormat initialValue() {
				return new SimpleDateFormat(pattern);
			}
		};

		public Date parse(String str) throws ParseException {
			return threadLocal.get().parse(str);
		}

		public String format(Date date) {
			return threadLocal.get().format(date);
		}
	}

}
